package com.hn658.groupshare.frontend.action.account.impl;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import javax.ws.rs.Consumes;
import javax.ws.rs.POST;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import javax.ws.rs.core.Context;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;

import com.hn658.framework.common.AbstractBaseService;
import com.hn658.framework.common.IServiceResponse;
import com.hn658.framework.shared.constants.CommonConstants;
import com.hn658.framework.shared.context.UserContext;
import com.hn658.framework.shared.exception.BusinessException;
import com.hn658.groupshare.account.entity.UserAccountEO;
import com.hn658.groupshare.account.exception.UserAccountException;
import com.hn658.groupshare.account.service.IUserAccountService;
import com.hn658.groupshare.common.enums.VerifyCodeType;
import com.hn658.groupshare.common.vo.CommonResponse;
import com.hn658.groupshare.frontend.action.account.IUserAccountAction;
import com.hn658.groupshare.frontend.action.account.vo.UserInfoRequest;
import com.hn658.groupshare.frontend.action.account.vo.UserInfoResponse;
import com.hn658.groupshare.frontend.util.AuthCookieEditor;
import com.hn658.groupshare.security.exception.VerifyException;
import com.hn658.groupshare.security.service.IVerifyCodeService;

/**
 * 用户登录或者注册
 * 
 * @ClassName: UserAccountActionImpl
 * @author davidcun
 * @date 2015年1月26日 上午11:46:00
 */
@Controller("userAccountAction")
@Path("userAccount")
@Produces("application/json; charset=UTF-8")
@Consumes("application/json; charset=UTF-8")
public class UserAccountActionImpl extends AbstractBaseService implements
		IUserAccountAction {

	@Autowired
	private IUserAccountService userAccountService;
	@Autowired
	private IVerifyCodeService verifyCodeService;

	/**
	 * 用户登录
	 * 
	 * @param userInfoRequest
	 * @param request
	 * @param response
	 * @return
	 */
	@Path("login")
	@POST
	public IServiceResponse login(UserInfoRequest userInfoRequest,
			@Context HttpServletRequest request,
			@Context HttpServletResponse response) {

		UserInfoResponse userInfoResponse = new UserInfoResponse();
		try {
			UserAccountEO userInfo = userAccountService
					.findUserByMobilePhone(userInfoRequest.getMobilePhone());
			if (userInfo == null) {
				throw new UserAccountException(
						UserAccountException.AccountNotExitedWrong);
			}
			if (StringUtils.isEmpty(userInfoRequest.getVerifyCode())) {
				throw new VerifyException(VerifyException.VerifyCodeNotEmpty);
			}
			String code = verifyCodeService.getMobileVerifyCode(
					userInfoRequest.getMobilePhone(),
					VerifyCodeType.MOBILE_LOGIN);
			if (StringUtils.isEmpty(code)
					|| !code.equals(userInfoRequest.getVerifyCode())) {
				throw new VerifyException(VerifyException.VerifyCodeError);
			} else {
				// 验证通过,删除验证码
				verifyCodeService.delectMobileVerifyCode(
						userInfoRequest.getMobilePhone(),
						VerifyCodeType.MOBILE_LOGIN);
			}
			// 登录成功
			// 创建会话Session
			String authkey = userAccountService.createSession(userInfo.getId());
			// 获取会话
			HttpSession session = request.getSession();
			session.setAttribute(CommonConstants.SERVICE_REQUEST_HEADER_UID,
					userInfo.getId().toString());
			session.setAttribute(
					CommonConstants.SERVICE_REQUEST_HEADER_AUTHKEY, authkey);

			// 这时跳转到index.jsp 根据session生成cookie
			AuthCookieEditor.saveCookie(request, response);
			userInfoResponse.setUserInfo(userInfo);

			this.success(userInfoResponse);
		} catch (BusinessException e) {
			this.error(userInfoResponse, e);
		}
		return userInfoResponse;
	}

	/**
	 * 用户退出或注销
	 * 
	 * @param request
	 * @param response
	 * @return
	 */

	@Path("logout")
	@POST
	public IServiceResponse logout(@Context HttpServletRequest request,
			@Context HttpServletResponse response) {
		String uid = (String) request.getSession().getAttribute(
				CommonConstants.SERVICE_REQUEST_HEADER_UID);
		userAccountService.removeSession(Long.valueOf(uid));
		CommonResponse commonResponse = new CommonResponse();
		// 失效Cookie
		AuthCookieEditor.invalidateCookie(request, response);
		this.success(commonResponse);
		return commonResponse;
	}

	/**
	 * 用户注册
	 */
	@Path("regist")
	@POST
	public IServiceResponse regist(UserInfoRequest userInfoRequest,
			@Context HttpServletRequest request,
			@Context HttpServletResponse response) {

		UserInfoResponse userInfoResponse = new UserInfoResponse();
		try {
			String code = verifyCodeService.getMobileVerifyCode(
					userInfoRequest.getMobilePhone(),
					VerifyCodeType.MOBILE_LOGIN);
			if (StringUtils.isEmpty(code)
					|| !code.equals(userInfoRequest.getVerifyCode())) {
				throw new VerifyException(VerifyException.VerifyCodeError);
			}
			UserAccountEO userInfo = userAccountService
					.findUserByMobilePhone(userInfoRequest.getMobilePhone());
			if (userInfo != null) {
				throw new UserAccountException(
						UserAccountException.AccountMobilePhoneEmpty);
			}
			userInfo = new UserAccountEO();
			userInfo.setMobilePhone(userInfoRequest.getMobilePhone());
			userInfo = userAccountService.register(userInfo);
			// 用户注册成功后设置为登录状态
			// 创建会话Session
			String authkey = userAccountService.createSession(userInfo.getId());
			// 获取会话
			HttpSession session = request.getSession();
			session.setAttribute(CommonConstants.SERVICE_REQUEST_HEADER_UID,
					userInfo.getId().toString());
			session.setAttribute(
					CommonConstants.SERVICE_REQUEST_HEADER_AUTHKEY, authkey);

			// 这时跳转到index.jsp 根据session生成cookie
			AuthCookieEditor.saveCookie(request, response);
			userInfoResponse.setUserInfo(userInfo);

			this.success(userInfoResponse);
		} catch (BusinessException e) {
			this.error(userInfoResponse, e);
		}
		return userInfoResponse;
	}

	/**
	 * 得到当前用户
	 * 
	 * @return
	 */
	@Path("queryCurrentUserInfo")
	@POST
	public IServiceResponse queryCurrentUserInfo() {
		UserInfoResponse response = new UserInfoResponse();
		UserAccountEO bui = (UserAccountEO) UserContext.getCurrentUser();
		response.setUserInfo(bui);
		this.success(response);
		return response;
	}

	/**
	 * 
	 * 核对验证码
	 * 
	 * @return
	 */
	@Path("checkVerifyCode")
	@POST
	public IServiceResponse verifyCode(UserInfoRequest request) {
		UserInfoResponse response = new UserInfoResponse();
		try {
			String code = verifyCodeService.getMobileVerifyCode(
					request.getMobilePhone(), VerifyCodeType.MOBILE_LOGIN);
			if (StringUtils.isEmpty(code)
					|| !code.equals(request.getVerifyCode())) {
				response.setStatus(false);
			} else {
				response.setStatus(true);
			}
			this.success(response);
		} catch (BusinessException e) {
			this.error(response, e);
		}
		return response;
	}

}
